import json
from pyecharts.charts import Map
from pyecharts import options as opts

# 常量定义
DATA_FILE_PATH = r"D:\itheima\Python\可视化案例数据\地图数据\疫情.txt"
OUTPUT_FILE = "河南省疫情地图.html"

# 读取数据文件
with open(DATA_FILE_PATH, "r", encoding="utf-8") as f:
    data = f.read()

# 解析JSON数据
json_data = json.loads(data)

# 提取河南省的数据
henan_data = json_data["areaTree"][0]["children"][3]["children"]

# 构建数据列表
data_list = [
    [city["name"] + "市", city["total"]["confirm"]]
    for city in henan_data
]

# 创建地图实例
map_chart = Map(init_opts=opts.InitOpts(width="1000px", height="800px"))

# 添加数据
map_chart.add(
    series_name="确诊人数",
    data_pair=data_list,
    maptype="河南",
    is_map_symbol_show=False,
    label_opts=opts.LabelOpts(is_show=True, font_size=12)
)

# 设置全局配置
map_chart.set_global_opts(
    title_opts=opts.TitleOpts(
        title="河南省新冠肺炎确诊人数分布",
        subtitle="数据来源: 国家卫健委",
        pos_left="center",
        title_textstyle_opts=opts.TextStyleOpts(font_size=20)
    ),
    visualmap_opts=opts.VisualMapOpts(
        is_show=True,
        is_piecewise=True,
        pos_left="10%",
        pos_bottom="10%",
        pieces=[
            {"min": 1, "max": 9, "label": "1-9人", "color": "#FFE6E6"},
            {"min": 10, "max": 99, "label": "10-99人", "color": "#FFC4C4"},
            {"min": 100, "max": 499, "label": "100-499人", "color": "#FF8080"},
            {"min": 500, "max": 999, "label": "500-999人", "color": "#FF4040"},
            {"min": 1000, "label": "1000人以上", "color": "#FF0000"},
        ],
        orient="horizontal"
    ),
    tooltip_opts=opts.TooltipOpts(
        trigger="item",
        formatter="{b}<br/>确诊人数: {c}"
    )
)

# 渲染图表
map_chart.render(OUTPUT_FILE)
print(f"地图生成成功，已保存为 {OUTPUT_FILE}")
